/*
 * Copyright 2009 Prime Technology.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.primefaces.optimus.config;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletContext;

import com.google.inject.Inject;
import com.google.inject.Injector;

public class OptimusBeanContext {

	private Map<String,BeanInfo> beans;
	
	private Injector injector;
	
	private ServletContext servletContext;

	@Inject
	private AnnotationScanner scanner;

	public void initialize(ServletContext servletContext, Injector injector) {
		this.injector = injector;
		this.servletContext = servletContext;
		
		scanner.scan(servletContext);
		
		beans = new HashMap<String, BeanInfo>();
		beans.putAll(scanner.getLazyControllers());
		beans.putAll(scanner.getStartupControllers());
		
		initializeStartupControllers(scanner.getStartupControllers());
	}
	
	public BeanInfo getBeanInfo(String name) {
		return beans.get(name);
	}
	
	public void setScanner(AnnotationScanner scanner) {
		this.scanner = scanner;
	}
	
	public ServletContext getServletContext() {
		return servletContext;
	}
	
	protected void initializeStartupControllers(Map<String,BeanInfo> controllers) {
		for (Iterator<String> iterator = controllers.keySet().iterator(); iterator.hasNext();) {
			String key = iterator.next();
			BeanInfo beanInfo = controllers.get(key);
			Class<?> clazz = beanInfo.getClazz();
			
			Object startedUpBean = injector.getInstance(clazz);
			servletContext.setAttribute(beanInfo.getName(), startedUpBean);
		}
	}
}